package com.tfswx.fljdmxyy.validation;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.HashMap;
import java.util.Map;

/**
 * 开始时间和结束时间的校验
 *
 * @author ricky
 * @date 2021/11/30
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UrlValid.Validator.class)
public @interface UrlValid {
    /**
     * 在线检测
     *
     * @return
     */
    boolean online() default true;

    String message() default "{path}-{errmsg}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    @Slf4j
    class Validator implements ConstraintValidator<UrlValid, String> {

        boolean online;

        @Override
        public void initialize(UrlValid constraintAnnotation) {
            online = constraintAnnotation.online();
        }

        @Override
        public boolean isValid(String url, ConstraintValidatorContext context) {
            if (StringUtils.isBlank(url)) {
                return true;
            }
            // 检查Url格式
            boolean isUrl = url.matches("https?://[\\w]+(\\.[\\w]+)+(:\\d+)?");
            if (!isUrl) {
                Map<String, String> map = new HashMap<>(1);
                map.put("errmsg", "格式不正确（http/https://xxx.xxx:8080）");
                ValidUtil.setParam(context, map);
                return false;
            }
            if (online) {
                try {
                    new RestTemplate().optionsForAllow(url);
                } catch (ResourceAccessException | HttpServerErrorException | HttpClientErrorException e) {
                    return true;
                } catch (Exception e) {
                    Map<String, String> map = new HashMap<>(1);
                    map.put("errmsg", "服务离线或其他错误：" + e.getMessage());
                    ValidUtil.setParam(context, map);
                    return false;
                }
            }

            return true;
        }
    }
}
